package com.hourupdate.network.server;


import java.net.Socket;
import java.util.Vector;

public class IMAHandler implements Runnable {
    //  Share Data
    private static Vector<IMAHandler> handlers = new Vector<IMAHandler>();

    //  Attribute
    private Connection _connect;
    private Thread     _thread;

    //  Constructor
    public IMAHandler(Socket connect) {
        _connect = new Connection(connect, false);
        _thread  = null;
    }

    //  Start
    public void start() {
        if (_thread == null) {
            _thread = new Thread(this, "ChatRoomHandler" + handlers.size());
            _thread.start();
        }
    }

    //  Run
    public void run() {
        handlers.add(this);

        String in;

        while ((in = _connect.readLine()) != null) {
            broadcast(in);
        }

        handlers.remove(this);

        stop();
    }

    //  Broadcast
    private void broadcast(String out) {
        synchronized (handlers) {
            for (IMAHandler handler : handlers) {
                if (!handler.equals(this)) {
                    handler._connect.writeLine(out);
                }
            }
        }
    }

    //  Stop
    public void stop() {
        _connect.close();
        _thread = null;
    }
}